import { Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core';
import { MemberStorageService } from 'src/app/services/member-storage.service';
@Component({
  selector: 'app-member-local-avatar',
  template: `<img [src]="avatarURL" [ngStyle]="scaleSize"/>`,
  styles: [``]
})
export class MemberLocalAvatarComponent implements OnInit, OnChanges {
  //编码后的头像地址
  @Input('link')
  public encodeAvatarLink!: string;
  @Input('scale')
  public scale: number = 32;
  public scaleSize: any = { "width": "32px", "height": "32px" };
  public defAvatar: string = 'assets/avatar/empty.png';
  public avatarURL!: string;

  /**
   * 可能由于缓存不是最新的,不会发出单独的请求
   * @param memberStorage 
   */
  constructor(private memberStorage: MemberStorageService) {}

  ngOnChanges(changes: SimpleChanges): void {
    if(changes['encodeAvatarLink'].firstChange){
      console.log('[MemberLocalAvatar-Emd]is first');
      return;
    }
    console.log('[MemberLocalAvatar-Emd]is not first');
    if(changes['encodeAvatarLink'].previousValue != changes['encodeAvatarLink'].currentValue){
      this.encodeAvatarLink = changes['encodeAvatarLink'].currentValue;
      this.decodeAvatarPath();
    }
  }

  ngOnInit(): void {
    this.decodeAvatarPath();
  }

  private decodeAvatarPath(): void{
    if (this.scale !== 32) {
      this.scaleSize = { "width": this.scale + "px", "height": this.scale + "px" };
    }
    this.avatarURL = this.memberStorage.decodeLocalAvatar(this.encodeAvatarLink)??this.defAvatar;
  }
}
